<?php
Class BaseModel
{
    private $userclass;
    private $link;
    private $sql_function;

    function basemodel($action)
    {
        global $config;

    $this->userclass = $action;
    $this->link = mysql_connect($config['host'], $config['uname'], $config['pwd']) or
                      die('Cannot connect to host: ' . mysql_error());
    mysql_select_db($config['dbname']);
    $this->sql_function = Array("CURDATE()", "NOW()");
    }

    function select_db($dbname)
    {
        return mysql_select_db($dbname);
    }

    function error_msg($mysql_error = "", $err_msg = "")
    {
        die("<h4> MySQL Error @ " . $_SERVER['PHP_SELF'] . " from class " . $this->userclass . "</h4>
          <h5>" . htmlentities($err_msg) . "</h5>
          <h5>" . htmlentities($mysql_error) . "</h5>");
    }

    # Get the last inserted id.
    function last_insert_id($table)
    {
         $query = "SELECT LAST_INSERT_ID() AS id FROM `$table`";
         $id = $this->query($query, true);
         return $id[0]['id'];
    }

    # Perform an insertion on $table, using the hash $values, whose keys
    # are the fields in the table and whose values are the values to
    # be inserted.
    function insert($table, $values, $insert = 'INSERT')
    {
        # initialize with open parens
        $ftxt = $vtxt = "(";

        # Iterate over the values hash
        $first = true;
    foreach ($values as $key => $val) {
        if ($first) {
            $first = false;
            } else {
            $ftxt .= ", ";
                $vtxt .= ", ";
            }
        $ftxt .= "`" . mysql_escape_string($key) . "`";

        # SQL functions are not quoted or escaped...
        if (array_search($val, $this->sql_function)) {
            $vtxt .= $val;
        } else {
            $vtxt .= "'" . mysql_escape_string($val) . "'";
        }
    }
    $ftxt .= ")";
    $vtxt .= ")";

    $query = "$insert INTO `" . mysql_escape_string($table) . "` " . $ftxt . " VALUES " . $vtxt;
    $this->query($query);
	$id = $this->query("SELECT LAST_INSERT_ID();", true);
	return $id[0][0];    
    }

    # Delete from $table against $fieldhash.  $fieldhash is a hash
    # whose keys are the names of the fields and whose values are the values
    # one wants to delete.  For example, if $values = ('foo' => 'bar',
    # 'baz' => 'quux') against a table 'blarg', this function will do
    # a DELETE FROM blarg WHERE foo = 'bar' AND baz = 'quux'.
    # The optional $extra parameter is an extra constraint on the query
    # and is included as an AND at the end of the query.
    #
    # Be warned: If $fieldhash and $extra are both empty, it will delete
    # everything from the table specified!  To protect the innocent, unlike
    # query_record, $fieldhash must always be specified explicitly.
    function delete_record($table, $fieldhash, $extra = "")
    {
        # Construct the clause on the query
    $fieldstr = "";
    $first = true;
    foreach ($fieldhash as $key => $val) {
        if ($first) {
            $first = false;
        } else {
            # If not the first, put an AND in between
        $fieldstr .= " AND ";
        }

        $fieldstr .= "`" . $key . "` = '" . mysql_escape_string($val) . "'";
    }

    # See to it that any $extra gets properly constructed.  If there
    # is nothing, then simply put nothing.  Check if the resulting
    # $fieldstr is empty -- if it isn't add an 'AND' before the $extra.
    $extra = ($extra == "") ? "" : (($fieldstr == "") ? $extra : ' AND ' . $extra);

    # If the clause is empty, then don't put a WHERE.
    $clause = $fieldstr . $extra;
    $clause = ($clause == "") ? "" : " WHERE " . $clause;

    $query = "DELETE FROM `" . mysql_escape_string($table) . "`" . $clause;
    return $this->query($query);
    }

    # Update a record in table $table to $value using the $where
    # constraint.  To prevent this function from causing undue damage,
    # $where must always be explicitly specified.
    function update($table, $value, $where)
    {
        $sets = array();
    foreach ($value as $key => $val) {
        # SQL functions are not quoted or escaped...
        if (!array_search($val, $this->sql_function)) {
            $vtxt = "'" . mysql_escape_string($val) . "'";
        } else {
            $vtxt = $val;
        }
        $sets[] = "`" . mysql_escape_string($key) . "` = " . $vtxt;
    }

    $where = ($where) ? (" WHERE " . $where) : "";
    $query = "UPDATE `" . mysql_escape_string($table) . "` SET " . implode(", ", $sets) . $where;
    return $this->query($query);
    }

    # Do an arbitrary database query.  $query is the SQL query to
    # be executed.  It will return the result of the query as is, or
    # the result set as an array if $fetcharray is true.
    function query($query, $fetcharray = false)
    {
       $result = @mysql_query($query, $this->link) or $this->error_msg(mysql_error(). ". Error in mysql query {$query}.");
       if($fetcharray){
           # Build $result as an array.
       $res = $result;
       $result = array();
	   #MYSQL_BOTH
       while($line = mysql_fetch_array($res, MYSQL_BOTH)){
           $result[] = $line;
       }
       }
       return $result;
   }

	function select_all($query)
	{
       $res = @mysql_query($query, $this->link) or $this->error_msg(mysql_error(). ". Error in mysql query {$query}.");
       $result = array();
       while($line = mysql_fetch_array($res, MYSQL_ASSOC)){
           $result[] = $line;
       }
       return $result;
	}

	function select_one($query)
	{
       $res = @mysql_query($query, $this->link) or $this->error_msg(mysql_error(). ". Error in mysql query {$query}.");
       $result = '';
       while($line = mysql_fetch_array($res, MYSQL_BOTH)){
           $result = $line;
       }
       return $result;
	}

    # Perform a query on $table against $fieldhash.  $fieldvals is a hash
    # whose keys are the names of the fields and whose values are the values
    # one wants to obtain.  For example, if $values = ('foo' => 'bar',
    # 'baz' => 'quux') against a table 'blarg', this function will do
    # a SELECT * FROM blarg WHERE foo = 'bar' AND baz = 'quux'.
    # The optional $extra parameter is an extra constraint on the query
    # and is included as an AND at the end of the query.  The $fields
    # parameter should be a proper SQL field specifier.  The default is '*'.
    function query_record($table, $fieldhash = array(), $fields="*", $extra = "")
    {
        # Construct the clause on the query
        $fieldstr = "";
        $first = true;
        foreach ($fieldhash as $key => $val) {
            if ($first) {
            $first = false;
            } else {
               # If not the first, put an AND in between
               $fieldstr .= " AND ";
            }
            $fieldstr .= "`" . $key . "` = '" . mysql_escape_string($val) . "'";
        }

        # See to it that any $extra gets properly constructed.  If there
        # is nothing, then simply put nothing.  Check if the resulting
        # $fieldstr is empty -- if it isn't add an 'AND' before the $extra.
        $extra = ($extra == "") ? "" : (($fieldstr == "") ? $extra : ' AND ' . $extra);

        # If the clause is empty, then don't put a WHERE.
        $clause = $fieldstr . $extra;
        $clause = ($clause == "") ? "" : " WHERE " . $clause;

        $query = "SELECT ". $fields . " FROM `" . mysql_escape_string($table) . "`" . $clause;
        return $this->query($query);
    }

    # Count the number of results for a query on $table against $fieldhash.
    # It returns the size of the result set were query_record to be used
    # on it.
    function count_record($table, $fieldhash = array(), $extra = "")
    {
        # Construct the clause on the query
        $fieldstr = "";
        $first = true;
        foreach ($fieldhash as $key => $val) {
            if ($first) {
            $first = false;
        } else {
            # If not the first, put an AND in between
                $fieldstr .= " AND ";
            }
        $fieldstr .= "`" . $key . "` = '" . mysql_escape_string($val) . "'";
        }

        # See to it that any $extra gets properly constructed.  If there
        # is nothing, then simply put nothing.  Check if the resulting
        # $fieldstr is empty -- if it isn't add an 'AND' before the $extra.
        $extra = ($extra == "") ? "" : (($fieldstr == "") ? $extra : ' AND ' . $extra);

        # If the clause is empty, then don't put a WHERE.
        $clause = $fieldstr . $extra;
        $clause = ($clause == "") ? "" : " WHERE " . $clause;

        $query = "SELECT COUNT(*) FROM `" . mysql_escape_string($table) . "`" . $clause;
        $res = $this->query($query, true);
        return $res[0][0];
    }
}
?>
